package TCPdemo;

import com.sun.security.ntlm.Server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;


/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-10-11
 * Time: 23:03
 */
public class TCPechoserver {
    private ServerSocket server = null;

    public TCPechoserver(int port) throws IOException {
        server = new ServerSocket(port);
    }

    public void start() throws IOException {
        while (true){
            Socket client = server.accept();
            work(client);
        }
    }

    public static void work(Socket client) throws IOException {
        System.out.printf("客户端：%s 在端口号 %d 上线\n", client.getInetAddress().toString(), client.getPort());
        try(InputStream inputStream = client.getInputStream();
            OutputStream outputStream = client.getOutputStream()) {
            while (true){
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()){
                    break;
                }
                String req = scanner.next();
                String resp = process(req);
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(resp);
                writer.flush();
                System.out.printf("[%s: %d] req: %s, res: %s\n", client.getInetAddress().toString(), client.getPort(),
                        req, resp);
            }
            System.out.printf("客户端：%s 在端口号 %d 下线\n", client.getInetAddress().toString(), client.getPort());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            client.close();
        }
    }

    public static String process(String str){
        return str;
    }

    public static void main(String[] args) throws IOException {
        TCPechoserver server = new TCPechoserver(9090);
        server.start();
    }
}
